//
//  Request.m
//  NewsReader
//
//  Created by blacksun on 11-2-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Request.h"


@implementation Request

@synthesize delegate;
@synthesize urlStr;
@synthesize command;
@synthesize currentConnection;
@synthesize responseData;


-(void)start{
	NSMutableData *data = [[NSMutableData alloc] init];
	self.responseData = data;
	[data release];
	NSURL *url = [[NSURL alloc] initWithString:self.urlStr];
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	self.currentConnection = connection;
	[connection release];
	[request release];
	[url release];
}
-(void)cancel{
	[self.currentConnection cancel];
	self.currentConnection = nil;
	self.responseData = nil;
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    self.responseData = nil;
    self.currentConnection = nil;
	[self.delegate request:self failedWithStatuCode:0 andCommand:self.command];
}



-(id)init{
	return [self initWithURLStr:nil delegate:nil andCommand:0];
}

-(id)initWithURLStr:(NSString *)aUrlStr delegate:(id<RequestDelegate>) aDelegate andCommand:(int)aCommand{
	if (self = [super init]) {
		self.urlStr = aUrlStr;
		self.delegate = aDelegate;
		self.command = aCommand;
		return self;
	}
	return nil;
}

-(void) dealloc{
	self.urlStr = nil;
	self.delegate = nil;
	self.currentConnection = nil;
	self.responseData = nil;
	[super dealloc];
}
@end
